<template>
  <div class="container" v-if="finish">
    <Navbar :title="title"></Navbar>
    <video :src="source" controls :poster="cover"></video>
    <van-tabs v-model="active" color="#3ca7fa" title-active-color="#3ca7fa" line-width="20px">
      <Directory :chapters="chapters" :videos="videos" ref="Directory"></Directory>
      <Comment :comments="comments" :user="user" @comment="comment" ref="Comment"></Comment>
    </van-tabs>
  </div>
</template>

<script>
import Navbar from '@/components/common/Navbar';
import Directory from '@/components/common/Directory';
import Comment from '@/components/common/Comment';
import { getOtherConfig } from '@/network/member';
import {
  getVideoDetail, getVideoSource, getVideoComments, commentCourse,
} from '@/network/video';
import { Notify } from 'vant';

export default {
  components: {
    Navbar,
    Directory,
    Comment,
  },
  data() {
    return {
      title: '',
      source: '',
      cover: '',
      active: 0,
      chapters: [],
      videos: [],
      user: {},
      comments: [],
      content: '',
      finish: false,
    };
  },
  methods: {
    goStudy() {
      this.$refs.Directory.goStudy();
    },
    getComments() {
      getVideoComments(this.$route.query.id).then((res) => {
        this.user = res.data.users;
        this.comments = res.data.comments;
        setTimeout(() => {
          this.finish = true;
        }, 800);
      });
    },
    comment(content) {
      commentCourse(this.$route.query.id, { content }).then((res) => {
        if (res.code != 0) return Notify(res.message);
        Notify({ type: 'success', message: '评论成功' });
        this.$refs.Comment.content = '';
        this.getComments();
      });
    },
    init() {
      getVideoDetail(this.$route.query.id).then((res) => {
        this.title = res.data.video.title;
        this.chapters = res.data.chapters;
        this.videos = res.data.videos;
        document.title = res.data.course.title;
      });
      getVideoSource(this.$route.query.id).then((res) => {
        this.source = res.data.urls[0].url;
      });
      getOtherConfig().then((res) => {
        this.cover = res.data.player.cover;
      });
      this.getComments();
    },
  },
  created() {
    this.init();
  },
  beforeRouteUpdate(to, from, next) {
    Object.assign(this.$data, this.$options.data());
    next();
    this.init();
  },
};
</script>

<style lang="less" scoped>
video {
  width: 100%;
}
</style>
